package com.crazy.jiakoulachang.service.impl;

import com.alibaba.excel.util.StringUtils;
import com.crazy.jiakoulachang.common.Constant;
import com.crazy.jiakoulachang.exception.ExceptionEnum;
import com.crazy.jiakoulachang.exception.MallException;
import com.crazy.jiakoulachang.mapper.RoleMapper;
import com.crazy.jiakoulachang.pojo.Role;
import com.crazy.jiakoulachang.service.RoleService;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;


/**
 * @author: 卢辉宇
 * @date: 2023/3/15 21:43
 * @description:
 */
@Service
public class RoleServiceImpl implements RoleService {

    @Resource
    private RoleMapper roleMapper;

    @Override
    public Role login(String userAccount, String password, HttpServletRequest request) throws MallException {
        // 1. 校验
        if (StringUtils.isBlank(userAccount)) {
            throw new MallException(ExceptionEnum.PARAMS_ERROR, "账号不能为空");
        }
        if (StringUtils.isBlank(password)) {
            throw new MallException(ExceptionEnum.PARAMS_ERROR, "密码不能为空");
        }
        // 2. 加密
        String encryptPassword = DigestUtils.md5DigestAsHex((Constant.SALT + password).getBytes());
//        String encryptPassword = password;
        // 查询用户是否存在
        Role role = roleMapper.selectByAccountAndPassword(userAccount, encryptPassword);

        // 用户不存在
        if (role == null) {
            throw new MallException(ExceptionEnum.PARAMS_ERROR, "用户不存在或密码错误");
        }

        //把敏感信息设空
        role.setUserPassword(null);
        // 3. 记录用户的登录态
        request.getSession().setAttribute(Constant.USER_LOGIN_STATE, role);
        return role;
    }

    @Override
    public long register(String userAccount, String password, String checkPassword) throws MallException {
        // 1. 校验
        if (StringUtils.isBlank(userAccount)) {
            throw new MallException(ExceptionEnum.PARAMS_ERROR, "账号不能为空");
        }
        if (StringUtils.isBlank(password)) {
            throw new MallException(ExceptionEnum.PARAMS_ERROR, "密码不能为空");
        }
        if (StringUtils.isBlank(checkPassword)) {
            throw new MallException(ExceptionEnum.PARAMS_ERROR, "再次密码不能为空");
        }
        if (userAccount.length() < 4) {
            throw new MallException(ExceptionEnum.PARAMS_ERROR, "用户账号过短");
        }
        if (password.length() < 8) {
            throw new MallException(ExceptionEnum.PARAMS_ERROR, "用户密码过短");
        }
        // 密码和校验密码相同
        if (!password.equals(checkPassword)) {
            throw new MallException(ExceptionEnum.PARAMS_ERROR, "两次输入的密码不一致");
        }
        synchronized (userAccount.intern()) {
            // 账户不能重复
            long count = roleMapper.selectByAccount(userAccount);
            if (count > 0) {
                throw new MallException(ExceptionEnum.PARAMS_ERROR, "账号名已存在");
            }
            // 2. 加密
            String encryptPassword = DigestUtils.md5DigestAsHex((Constant.SALT + password).getBytes());
//            String encryptPassword =password;
            // 3. 插入数据
            Role role = new Role();
            role.setUserAccount(userAccount);
            role.setUserPassword(encryptPassword);
            boolean saveResult = roleMapper.save(role);
            if (!saveResult) {
                throw new MallException(ExceptionEnum.SYSTEM_ERROR, "注册失败，数据库错误");
            }
            Role role1 = roleMapper.selectByAccountAndPassword(userAccount, encryptPassword);
            return role1.getId();
        }
    }

    /**
     * 获取当前登录用户
     *
     * @param request
     * @return
     */
    @Override
    public Role getLoginRole(HttpServletRequest request) throws IOException {
        //得到请求后的响应对象
        HttpServletResponse response = ((ServletRequestAttributes) RequestContextHolder.currentRequestAttributes()).getResponse();
        // 先判断是否已登录
        Object userObj = request.getSession().getAttribute(Constant.USER_LOGIN_STATE);
        Role currentUser = (Role) userObj;
        if (currentUser == null || currentUser.getId() == null) {
            response.sendRedirect("/login.html");
            throw new MallException(ExceptionEnum.NOT_LOGIN_ERROR);
        }
        // 从数据库查询（追求性能的话可以注释，直接走缓存）
        long roleId = currentUser.getId();
        currentUser = roleMapper.selectById(roleId);
        if (currentUser == null) {
            response.sendRedirect("/login.html");
            throw new MallException(ExceptionEnum.NOT_LOGIN_ERROR);
        }
        return currentUser;
    }
}
